package com.roc.web.action.windcontroll;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.BlackListBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.MerinfoStop;
import com.roc.pojo.Operators;
import com.roc.service.IStopService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@Component
@Namespace("/stop")
@SuppressWarnings("serial")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class StopListAction  extends PaginationBaseAction {
	
	private Logger logger=LogManager.getLogger(StopListAction.class);
	private StopListSearchCondition searchCondition;
	
	private MerinfoStop stop;
	@Autowired
	IPageService pagenitionService;
	
	private File file;
	
	@Autowired
	IStopService stopService;
	
	
	/**
	 * 初始化证件限制
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/windControllSta/stopList.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;	   
    }
	/**
	 *  证件限制查询
	 * @Title:stopView
	 * @Description: TODO
	 * @param @return
	 * @param @throws Exception    
	 * @return String    
	 * @throws
	 */
	@Action(value = "stoplistview", results = { @Result(name = "success", location = "/pages/windControllSta/stopList.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String stopView() throws Exception{
		try {
			if(searchCondition==null){
				searchCondition=(StopListSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new StopListSearchCondition();
				}
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
				
				List<MerinfoStop> lists=new ArrayList<MerinfoStop>();
				if(searchRsList!=null&&searchRsList.size()>0)
				{
					Iterator<?> iterator=searchRsList.iterator();
					while(iterator.hasNext())
					{
						Object[] obj=(Object[]) iterator.next();
						MerinfoStop stop=new MerinfoStop();
						stop.setMid(Constance.Null2EmptyTrim(obj[0]));
						stop.setStatus(Constance.Null2EmptyTrim(obj[1]));
						stop.setCreatetime(Constance.Null2EmptyTrim(obj[2]));
						stop.setAgentName(Constance.Null2EmptyTrim(obj[3]));
						stop.setAgentId(Long.parseLong(Constance.Null2EmptyTrim(obj[4])));
						stop.setDetail(Constance.Null2EmptyTrim(obj[5]));
						lists.add(stop);
					}
					searchRsList.clear();
					searchRsList.addAll(lists);
				}
			}
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
	   return SUCCESS;
    }
	
	/**
	 * 进件限制详情显示
	 * @return
	 * @throws Exception
	 */
	@Action(value = "limitiDetilQuery", 
			results = { @Result(name = "success", location = "/pages/windControllSta/stopDetail.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String limitiDetilQuery() throws Exception{
		try {
		    init();
			if(stop.getMid()==null || stop.getMid().equals("")||stop.getStatus()==null||stop.getStatus().equals("")){
				addActionError("查询进件限制详情失败~！");
				return ERROR;
			}
			String card_type="";
			if(stop.getStatus().equals("1")){
				card_type="营业执照 ";
			}else if(stop.getStatus().equals("2")){
				card_type="结算卡号";
			}else if(stop.getStatus().equals("0")){
				card_type="法人证件号码";
			}else if(stop.getStatus().equals("3")){
				card_type="非法人身份证";
			}else if(stop.getStatus().equals("4")){
				card_type="手机号";
			}
			//进件限制信息
			searchRsList=stopService.limitiDetilQuery(stop.getMid(), stop.getStatus());
			List<Object> lists=new ArrayList<Object>();
			if(searchRsList!=null&&searchRsList.size()>0)
			{
				Iterator<?> iterator=searchRsList.iterator();
				while(iterator.hasNext())
				{
					Object[] obj=(Object[]) iterator.next();
					Map<String,String> map = new HashMap<String,String>();  
					map.put("mcht_cd", Constance.Null2EmptyTrim(obj[0]));
				    map.put("name", Constance.Null2EmptyTrim(obj[1]));
				    map.put("ins_name", Constance.Null2EmptyTrim(obj[2]));
				    map.put("oneagentname", Constance.Null2EmptyTrim(obj[3]));
				    map.put("companyname", Constance.Null2EmptyTrim(obj[4]));
					map.put("mid", Constance.Null2EmptyTrim(obj[5]));
					map.put("card_type",card_type);
					lists.add(map);
				}
				searchRsList.clear();
				searchRsList.addAll(lists);
			}
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);

    	}catch (Exception e) {
			logger.error(e.getMessage(),e);
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
			
		return SUCCESS;
	}
	
	/**
	 * 初始化添加黑名单
	 * @return
	 */
	@Action(value = "addStopjsp", results = { @Result(name = "success", location = "/pages/windControllSta/addStop.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addStopview()
	{
		stop=new MerinfoStop();
		stop.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		return SUCCESS;		
	}
	/**
	 * 添加黑名单
	 * @return
	 */
	@Action(value = "addStop", results = { @Result(name = "success", location = "/pages/windControllSta/stopList.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addStop()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			stopService.addStopList(stop,logingMerchant);
			addActionMessage("添加成功!");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("添加限制失败~");
		}
		return SUCCESS;		
	}
	
	/**
	 * 删除进件（证件）限时
	  * @Title: delBlackList
	  * @Description: TODO
	  * @param @return    
	  * @return String    
	  * @throws
	 */
	@Action(value = "delStoplist", results = { @Result(name = "success", type="json")})
	public String delStoplist()
	{
		try {
			
			stopService.deleteStopNum(stop.getMid());
			addActionMessage("删除成功!");
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("删除证件限制失败~");
		}
		return SUCCESS;
	}
	
	 /**
	  * 验证卡号或商户号是否已存在数据库中
	  */
	@Action(value="validateStop")
	public void validateStop()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		boolean value=true;
		try {
			stop=stopService.findByMid(stop.getMid());
			if(stop!=null)
			{
				value=false;
			}
			response.getWriter().print(value);
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("验证卡号或商户号错误!!!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 批量导入初始化页面
	 * @return
	 */
	@Action(value = "startExportJsp", results = { @Result(name = "success", location = "/pages/windControllSta/exportStop.jsp")
    })	
	public String moreBlackList()throws Exception
	{
		return SUCCESS;
	}
	
	/**
	 * 批量导入进件限制
	 * @return
	 */
	@Action(value = "addstoplist", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(name = "success",location = "/pages/windControllSta/stopList.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")})
	public String addStopLists()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, Object> resultMap=stopService.insertExportBlackList(file, logingMerchant);
			if(resultMap.containsKey("result"))
			{	
				Object objMsg=resultMap.get("result");
				addActionMessage(String.valueOf(objMsg));
			}		
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("批量导入进件限制失败~");
		}
		return SUCCESS;		
	}
	

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_STOP_LIST_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_STOP_LIST_QUERY);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE+"";
	}
	
	public StopListSearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(StopListSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public MerinfoStop getStop() {
		return stop;
	}
	public void setStop(MerinfoStop stop) {
		this.stop = stop;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}

}
